package cn.gs.serializable.old;

// @author gs
import cn.gs.util.stream.TokenReader;
import java.io.IOException;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class SerialString implements ISerialEntity {

    String t;

    @Override
    public <T> T deserialize(Class<T> clazz) {
        if (String.class.isAssignableFrom(clazz)) {
            return (T) t;
        } else if (Character.class.isAssignableFrom(clazz)) {
            return (T) Character.valueOf(t.charAt(0));
        } else if (Enum.class.isAssignableFrom(clazz)) {
            return (T) Enum.valueOf((Class) clazz, t);
        } else {
            return null;
        }
    }

    @Override
    public Object deserialize() {
        return t;
    }

    @Override
    public boolean serialize(Object o) {
        if (o == null) {
            return false;
        }
        if (o instanceof String || o instanceof Character || o instanceof Enum) {
            this.t = o.toString();
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void write(Writer writer) throws IOException {
        writer.write("\"" + SerialTransport.encode(t) + "\"");
    }

    @Override
    public boolean read(TokenReader reader) throws IOException {
        String s = reader.get();
        if ("\"".equals(s)) {
            t = reader.get();
            if ("\"".equals(t)) {
                t = "";
            } else {
                s = reader.get();
                if (!"\"".equals(s)) {
                    throw new IOException("Token Error: \" != " + s);
                }
            }
            t = SerialTransport.decode(t);
            return true;
        } else {
            reader.back();
            return false;
        }
    }

    @Override
    public String toString(String prefix) {
        return prefix + t;
    }

    @Override
    public String toString() {
        return toString("");
    }
}
